//
//  WRCollectionViewLineLayout.m
//  01-UICollectionView显示图片
//
//  Created by 紫荆秋雪 on 16/3/4.
//  Copyright © 2016年 紫荆秋雪. All rights reserved.
//

#import "WRCollectionViewLineLayout.h"

static CGFloat WRWH = 100;

@implementation WRCollectionViewLineLayout

- (instancetype)init
{

    self = [super init];
    if (self) {
        
    }
    
    return self;
}

- (void)prepareLayout
{

    //设置cell的尺寸
    self.itemSize = CGSizeMake(WRWH, WRWH);
    
    //设置滚动方向
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    //设置最小行间距
    self.minimumLineSpacing = 90;
    
    //设置显示的内容间距
    CGFloat inset = (self.collectionView.frame.size.width - WRWH) * 0.5;
    
    self.sectionInset = UIEdgeInsetsMake(0, inset, 0, inset);

    
}

#pragma mark - 设置图片在中心的位置
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{

    //1、获取滑动停止时的范围
    CGRect displayFrame;
    displayFrame.origin = proposedContentOffset;
    displayFrame.size = self.collectionView.frame.size;
    
    //2、获取中点
    CGFloat centerX = proposedContentOffset.x + self.collectionView.frame.size.width * 0.5;
    
    //3、通过遍历“停止时范围中的”属性
    CGFloat offsetMax = MAXFLOAT;
    NSArray *attrbles = [self layoutAttributesForElementsInRect:displayFrame];
    for (UICollectionViewLayoutAttributes *attr in attrbles) {
        
        //判断“最小值”
        if (ABS(attr.center.x - centerX) < (offsetMax)) {
            offsetMax = attr.center.x - centerX;

        }
    }

    return CGPointMake(proposedContentOffset.x + offsetMax, proposedContentOffset.y);
//    return CGPointMake(100, 0);
}

#pragma mark - 获取所有属性
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    //1、设置可见范围
    CGRect visible;
    visible.size = self.collectionView.frame.size;
    visible.origin = self.collectionView.contentOffset;

    
    //可见范围中心
    CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.frame.size.width * 0.5;
    

    //2、取出默认的cell
    NSArray *array = [super layoutAttributesForElementsInRect:rect];
    
    //3、通过遍历数组来设置每个cell的attributes
    for (UICollectionViewLayoutAttributes *attr in array) {
        
        //为了提高效率：只设置在可见范围中的attr
        if (!CGRectIntersectsRect(visible, attr.frame)) {
            continue;
        }
        
        CGFloat itmeX = attr.center.x;
        
        //设置方法系数
        CGFloat scole =1 + 0.8 * (1 - ABS(centerX - itmeX) / 150);
        
        attr.transform3D = CATransform3DMakeScale(scole, scole, 1.0);
    }
    
    return array;
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBound
{
    return YES;
}

@end
